package user.zc.excel.render;

import user.zc.excel.data.info.ICell;
import user.zc.excel.data.style.IStyle;
import org.apache.poi.xssf.usermodel.XSSFCell;

import java.math.BigDecimal;
import java.text.*;
import java.util.Date;

public interface ITransfter<T> {
    T execute(Object obj);

    class Context{
        static <T> void  set(XSSFCell cell, ICell.CellInfo<T> cellInfo){
            Object obj  = cellInfo.getData();
            IStyle.StyleInfo styleInfo = cellInfo.getStyleInfo();
            if(obj instanceof Integer){
                cell.setCellValue( new IntegerTransfter().execute(obj));
            }else if(obj instanceof Long){
                cell.setCellValue( new LongTransfter().execute(obj));
            }else if(obj instanceof BigDecimal){
                cell.setCellValue( new BigDecimalTransfter(styleInfo).execute(obj));
            }else if(obj instanceof Date){
                cell.setCellValue( new DateTransfter().execute(obj));
            }else{
                cell.setCellValue( new StringTransfter().execute(obj));
            }
        }
    }

    class LongTransfter implements ITransfter<Long>{
        @Override
        public Long execute(Object obj) {
            return (Long) obj;
        }
    }
    class IntegerTransfter implements ITransfter<Integer>{
        @Override
        public Integer execute(Object obj) {
            return (Integer) obj;
        }
    }
    class DateTransfter implements ITransfter<String>{
        @Override
        public String execute(Object obj) {
            SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return myFmt.format((Date)obj);
        }
    }
    class StringTransfter implements ITransfter<String>{
        @Override
        public String execute(Object obj) {
            return (String) obj;
        }
    }

    class BigDecimalTransfter implements ITransfter<Double>{

        private IStyle.StyleInfo styleInfo;
        public BigDecimalTransfter(IStyle.StyleInfo styleInfo){
            this.styleInfo = styleInfo;
        }
        @Override
        public Double execute(Object obj) {
            obj = ((BigDecimal)obj).setScale(styleInfo.getPrecision(),BigDecimal.ROUND_HALF_UP);
            DecimalFormat df = new DecimalFormat("#." + "00000000".substring(0, styleInfo.getPrecision()));
            return Double.parseDouble(df.format(obj));
        }
    }

}
